package com.jingge.autojob.skeleton.model.task.remote;

import com.jingge.autojob.util.http.HttpUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.time.Duration;

/**
 * HTTP的请求处理
 *
 * @author JingGe(* ^ ▽ ^ *)
 * @date 2023-09-04 11:37
 * @email 1158055613@qq.com
 */
public class BaseJsonHttpRequestHandler implements RequestHandler {
    private final Request request;
    private long connectTimeout = 10000;
    private long readTimeout = 30000;
    private long writeTimeout = 30000;

    public BaseJsonHttpRequestHandler(Request request) {
        this(request, 10000, 30000, 30000);
    }

    public BaseJsonHttpRequestHandler(Request request, long connectTimeout, long readTimeout, long writeTimeout) {
        this.request = request;
        this.connectTimeout = connectTimeout;
        this.readTimeout = readTimeout;
        this.writeTimeout = writeTimeout;
    }

    @Override
    public RemoteResponse sendRequest() {
        Call call = HttpUtil.CLIENT
                .newBuilder()
                .connectTimeout(Duration.ofMillis(connectTimeout))
                .readTimeout(Duration.ofMillis(readTimeout))
                .writeTimeout(Duration.ofMillis(writeTimeout))
                .build()
                .newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new AutoJobRemoteTaskException(e);
        }
        return new HttpRemoteResponse(response);
    }
}
